#!/usr/bin/python

from pyPdf import PdfFileWriter, PdfFileReader
from reportlab.lib import pagesizes
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm, mm, inch
from StringIO import StringIO
from sys import argv,exit

if len(argv) == 1:
	exit('Modo de Uso: pdf-tools input-file.pdf file-model.txt [password]')
else:
	INPUT_PATH = argv[1]
	MODEL_PATH = argv[2]

def criarPdfModelo():
        buffer = StringIO()

        c = canvas.Canvas('pdf_modelo.pdf')
        c.showOutline()
	
	i = 1
	model_file = open(MODEL_PATH,'r')
	for line in model_file:
        	parametros = line.split()
	        if parametros[0] == 'rect':
        	        if len(parametros) != 6:
                	        exit("Erro na linha " + str(i) + " do arquivo " + MODEL_PATH +". Quantidade errada de parametros.")
			cores = parametros[5].split(',')
			c.setFillColorRGB( int(cores[0]), int(cores[1]), int(cores[2]) )
			c.rect( int(parametros[1])*mm, int(parametros[2])*mm, int(parametros[3])*mm, int(parametros[4])*mm, fill=1)
		
	        i = i + 1

	c.save()

        buffer.write(c.getpdfdata())
        buffer.seek(0)
        return buffer

# Classe para Encalpsular um PDF
class PdfWriter(object):
    def __init__(self, outputFile):
        self.outputWriter = PdfFileWriter()
        self.__outputFile = outputFile
       
    def savePdf(self):
        outputStream = file(self.__outputFile, "wb")
        self.outputWriter.write(outputStream)
        outputStream.close()
   
    def addPage(self, page):
        self.outputWriter.addPage(page)

criarPdfModelo()

outputFile = "arquivo_saida.pdf"

pdfWriter = PdfWriter(outputFile)
pdfinput = PdfFileReader(file( INPUT_PATH, "rb"))

if len(argv) > 3:
	print argv[3]
	resultado = pdfinput.decrypt(argv[3].encode('utf-8'))

pdfinput2 = PdfFileReader(file( 'pdf_modelo.pdf', "rb"))

totalPages = pdfinput.getNumPages()
print "Quantidade total de paginas:",totalPages
for i in range(totalPages):
	newpage = pdfinput.getPage(i)
	newpage.mergePage(pdfinput2.getPage(0))
	pdfWriter.addPage(newpage)
	porcentagem = (i*100)/totalPages
	print "[" + str(porcentagem)  + "%] ", "Gerando pagina", i
print "[100%] Gerando PDF, por favor, aguarge..."
pdfWriter.savePdf()
print "PDF gerado com sucesso!"
